import { fetchEventSource } from "@microsoft/fetch-event-source"
import { ChatApi } from "../constants/service-api"

export const useAIChatSse = () => {
  const isLoading = ref(false)
  const value = ref()
  const ctrl = new AbortController()

  const fetchChatData = async (message: string | number) => {
    try {
      isLoading.value = true
      await fetchEventSource(import.meta.env.EDUC_API_BASE_URL + ChatApi.CHAT_AI[1] + `?question=${message}`, {
        headers: {
          "Content-Type": "application/json"
        },
        onmessage(event) {
          if (event.data === "complete") return
          value.value = event.data
        },
        onclose() {
          console.log("连接关闭");
        },
        onerror(err) {
          ctrl.abort()
        },
        signal: ctrl.signal
      })
    } catch (error) {
      throw Error('获取信息失败:' + error)
    } finally {
      isLoading.value = false
    }

  }

  return {
    value,
    isLoading,
    fetchChatData
  }

}